<?php

// ------------------------------------------------------------------------
// |@Author       : Jarmin <edshop@qq.com>
// |@----------------------------------------------------------------------
// |@Date         : 2025-04-18 08:23:30
// |@----------------------------------------------------------------------
// |@LastEditTime : 2025-04-19 09:49:54
// |@----------------------------------------------------------------------
// |@LastEditors  : Jarmin <jarmin@ladmin.cn>
// |@----------------------------------------------------------------------
// |@Description  :
// |@----------------------------------------------------------------------
// |@FilePath     : WordImage.php
// |@----------------------------------------------------------------------
// |@Copyright (c) 2025 http://www.ladmin.cn   All rights reserved.
// ------------------------------------------------------------------------

declare(strict_types=1);

namespace think\captcha\domain\Logic;

use think\captcha\domain\vo\PointVo;
use Intervention\Image\Typography\FontFactory;
use think\captcha\utils\RandomUtils;

/**
 * 文字码图片处理
 * Class WordCaptchaEntity
 * @package think\captcha\domain\Entity
 */
class WordImage extends BaseImage
{
    /**
     * @var array
     */
    protected $wordList;

    /**
     * @return self
     */
    public function setWordList(array $wordList)
    {
        $this->wordList = $wordList;
        return $this;
    }

    public function getWordList()
    {
        return $this->wordList;
    }

    public function run()
    {
        $this->inputWords();
        $this->makeWatermark($this->backgroundVo->image);
    }

    /**
     * 写入文字
     */
    protected function inputWords()
    {
        foreach ($this->wordList as $key => $word) {
            $point = $this->point[$key];
            $this->backgroundVo->image->text($word, $point->x, $point->y, function (FontFactory $factory) {
                $factory->file($this->fontFile);
                $factory->size(BaseData::FONTSIZE);
                $factory->color(RandomUtils::getRandomColor());
                $factory->angle(RandomUtils::getRandomAngle());
                $factory->align('center');
                $factory->valign('center');
            });
        }
    }

    /**
     * 返回前端需要的格式
     * @return false|string[]
     */
    public function response()
    {
        $image = $this->getBackgroundVo()->image;
        $encodedImage = $image->encode();
        $mediaType = $encodedImage->mediaType();
        $base64Data = base64_encode((string) $encodedImage);
        $result = "data:{$mediaType};base64,{$base64Data}";
        //返回图片base64的第二部分
        return explode(',', $result)[1];
    }

    /**
     * 用来调试
     */
    public function echo()
    {
        die($this->getBackgroundVo()->image->response());
    }
}
